<template>
  <view class="page-container">
    <GlobalTopBar ref="topBarRef" class="topbars" color="#fff" :isLeft="true">
      <template #title
        ><text style="color: #fff">添加{{ dtext }}单</text></template
      >
    </GlobalTopBar>
    <!-- 内容 -->
    <view class="page_content">
      <!-- 基本信息  -->
      <view class="jbxx_title flex_jb"
        >基本信息
        <view class="bcBtn" @click="doSaveWarehouseOrder">保存</view></view
      >
      <view class="jb_center">
        <view class="flex jb border_b">
          <text>{{ dtext }}单编号</text>
          <text>{{ fromDttas.order_number }}</text>
        </view>
        <view class="flex jb border_b">
          <text>{{ dtext }}时间</text>
          <text>{{ fromDttas.order_time }}</text>
        </view>
        <view class="flex jb border_b">
          <text>{{ dtext }}仓库</text>
          <view class="flex">
            <picker
              @change="bindPickerChange"
              range-key="warehouse_title"
              :range="WarehouseList"
              class="flex"
            >
              <view class="flex">
                <input
                  style="text-align: right"
                  type="text"
                  disabled
                  :value="dText2"
                  placeholder="请选择仓库名称" />
                <uni-icons type="right" size="22" color="#999"></uni-icons
              ></view>
            </picker>
          </view>
        </view>
        <view class="flex jb border_b ac">
          <text style="margin-bottom: 20rpx"
            >{{ dtext }}凭证（最多上传5张）</text
          >
          <view>
            <view class="ulimgbox" v-if="imgList.length">
              <view
                class="lib"
                v-for="(item, index) in imgList"
                :key="index + 1"
              >
                <image :src="item" mode="aspectFill" />
                <view class="close2" @click="imgList.splice(index, 1)">
                  <image
                    class="close2_img"
                    :src="`${store.imgDomain}close2.png`"
                    mode="aspectFill"
                  />
                </view>
              </view>
            </view>

            <view class="addimg" @click="chooseImage" v-if="imgList.length < 5">
              <uni-icons
                class="flex_center"
                type="plusempty"
                size="30"
                color="#90beb7"
              ></uni-icons
            ></view>
          </view>
        </view>
        <view class="flex jb border_b ac">
          <text style="margin-bottom: 20rpx">备注</text>
          <view class="flex">
            <textarea
              style="font-size: 24rpx; width: 100%"
              v-model="fromDttas.remark"
              type="text"
              placeholder="请输入备注"
            />
          </view>
        </view>
      </view>

      <!-- 取货物料  -->
      <view class="jbxx_title flex_jb"
        >{{ dtext }}物料
        <view
          class="flex marginl"
          @click="store.to(`/pages/master/inventory/addtkd?type=${types}`)"
        >
          <uni-icons type="plus" size="24" color="#fff"></uni-icons>
          添加物料
        </view></view
      >
      <view
        class="center_li"
        v-for="(item, index) in warehouse_order_details_json_List"
        :key="index + 1"
      >
        <view class="border_b li_tops flex_jb">
          物料编码：{{ item.material_variant_number }}
          <uni-icons
            type="trash"
            size="22"
            @click="warehouse_order_details_json_List.splice(index, 1)"
          ></uni-icons
        ></view>
        <view class="title">{{ item.material_title }}</view>
        <view class="flex jb"
          ><text>规格型号：{{ item.material_variant_title }}</text
          ><text>×{{ item.count }}</text></view
        >
        <view class="flex jb"
          ><text>品牌：{{ item.material_brand }}</text
          ><text
            >售价：<text class="textac"
              >￥{{
                item.material_variant_sales_price || item.sales_price
              }}</text
            >
          </text></view
        >
      </view>
    </view>
  </view>
</template>

<script setup>
import { computed, reactive, ref, watch } from 'vue';
import { useCounterStore } from '@/store';
import tabBar from '@/components/tabBar.vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import request from '@/utils/request';
import { formatTimestamp } from '@/utils/validate';

const store = useCounterStore();
const fromDttas = reactive({
  main_type: 1,
  order_number: '',
  order_time: '',
  warehouse_id: '',
  img: '',
  warehouse_order_details_json: '',
  remark: '',
});
const warehouse_order_details_json_List = ref([]);
const dText2 = ref('');
const imgList = ref([]);
// 上传图
const chooseImage = () => {
  uni.chooseImage({
    count: 5 - imgList.value.length,
    sourceType: ['album', 'camera'], // 可选择相册或相机（拍照）
    success: (res) => {
      res.tempFilePaths.forEach((tempFilePath) => {
        onChooseAvatar(tempFilePath); // 单独的单张上传函数
      });
    },
    fail: (err) => {
      console.log('选择图片失败', err);
    },
  });
};
// 选择头像回调
const onChooseAvatar = (tempFilePaths) => {
  uni.uploadFile({
    url: 'https://adm.jinjiangservice.com/index.php/wxapp/common/uploadCommonImage',
    method: 'POST',
    filePath: tempFilePaths.detail?.avatarUrl || tempFilePaths,
    formData: {
      file: tempFilePaths.detail?.avatarUrl || tempFilePaths,
    },
    header: {
      'Content-Type': 'multipart/form-data',
    },
    name: 'file',
    success(res) {
      imgList.value.push(JSON.parse(res.data).data.path);
    },
  });
};
const WarehouseList = ref([]);
// 获取所有启用仓库备选数据
const getAllOpenWarehouseList = async () => {
  WarehouseList.value = await request(
    'worker/warehouse/getAllOpenWarehouseList',
  );
};

// 获取服务器时间戳
const getTimeStamp = async () => {
  const data = await request('wxapp/common/getTimeStamp');

  fromDttas.order_number =
    `${types.value === 1 ? 'QHD' : 'TKD'}` +
    data * 1000 +
    (Math.floor(Math.random() * 1001) + 1000);
  fromDttas.order_time = formatTimestamp(data, 'YYYY-MM-DD hh:mm:ss');
};

const bindPickerChange = (e) => {
  fromDttas.warehouse_id = WarehouseList.value[e.detail.value].id;
  dText2.value = WarehouseList.value[e.detail.value].warehouse_title;
};

// 保存取货单/退库单
const doSaveWarehouseOrder = async () => {
  if (!fromDttas.warehouse_id) {
    uni.showToast({
      title: '请选择仓库',
      icon: 'none',
    });
    return;
  }
  if (!imgList.value.length) {
    uni.showToast({
      title: '请上传凭证',
      icon: 'none',
    });
    return;
  }
  if (!warehouse_order_details_json_List.value.length) {
    uni.showToast({
      title: '请添加物料',
      icon: 'none',
    });
    return;
  }

  fromDttas.img = imgList.value.join(',');
  fromDttas.warehouse_order_details_json = JSON.stringify(
    warehouse_order_details_json_List.value.map((item) => ({
      material_variant_id: item.material_variant_id || item.id,
      count: item.count,
    })),
  );
  await request('worker/warehouse/doSaveWarehouseOrder', fromDttas, 'post');
  uni.navigateBack({
    delta: 1,
  });
};

onShow(() => {
  if (store.navigateBackData.id) {
    const iy = warehouse_order_details_json_List.value.findIndex(
      (i) =>
        i.id ===
        (store.navigateBackData.id ||
          store.navigateBackData.material_variant_id),
    );
    if (iy != -1) {
      warehouse_order_details_json_List.value[iy].count +=
        +store.navigateBackData.count;
      store.navigateBackData = {};
      return;
    }
    warehouse_order_details_json_List.value.push(store.navigateBackData);
    store.navigateBackData = {};
  }
});
const types = ref(1);
const dtext = computed(() => {
  return types.value === 1 ? '取货' : '退库';
});
onLoad((option) => {
  types.value = +option.type || 1;
  fromDttas.main_type = types.value;
  warehouse_order_details_json_List.value = [];
  getAllOpenWarehouseList();
  getTimeStamp();
});
</script>

<style scoped lang="scss">
.topbars {
  background: linear-gradient(to right, #2bc1ac, #10b3a2);
}
.page_content {
  background-color: #f8f8f8;
  overflow-y: auto;
  position: relative;
  box-sizing: border-box;
  padding: 20rpx 20rpx 30rpx;
}

.jbxx_title {
  position: relative;
  box-sizing: border-box;
  padding: 20rpx 0 20rpx 20rpx;
  font-size: 30rpx;
  &::after {
    content: ' ';
    position: absolute;
    top: 50%;
    left: 0;
    transform: translateY(-50%);
    height: 40rpx;
    width: 10rpx;
    border-radius: 5rpx;
    background-color: #15caba;
  }
}
.jb_center {
  background-color: #fff;
  border: 1rpx solid #7fd2ca;
  border-radius: 10rpx;
  box-sizing: border-box;
  padding: 0 20rpx;
  .jb {
    justify-content: space-between;
    box-sizing: border-box;
    padding: 20rpx;
    &.ac {
      align-items: flex-start;
      flex-direction: column;

      .flex {
        width: 100%;
      }
    }
    .addimg {
      position: relative;
      width: max-content;
      border-radius: 20rpx;
      border: 1rpx dashed #90beb7;
      color: #90beb7;
      font-size: 100rpx;
      padding: 50rpx;
    }
  }
}
.bcBtn {
  line-height: 60rpx;
  border-radius: 30rpx;
  color: #fff;
  padding: 0 40rpx;
  background-color: #13c4b4;
}
.marginl {
  width: max-content;

  background-color: #12c3b1;
  border-radius: 10rpx;
  box-sizing: border-box;
  padding: 10rpx 20rpx;
  color: #fff;
}
.center_li {
  margin-top: 20rpx;
  background-color: #fff;
  padding: 20rpx;
  border: 1rpx solid #7fd2cb;
  box-sizing: border-box;
  border-radius: 10rpx;
  .li_tops {
    box-sizing: border-box;
    padding: 0 0 20rpx 0;
    margin-bottom: 20rpx;
  }
  .title {
    font-size: 30rpx;
    font-weight: 600;
  }
  .jb {
    justify-content: space-between;
    margin-top: 10rpx;
  }
  .textac {
    color: #fb0201;
    font-size: 30rpx;
  }
}
.ulimgbox {
  margin: 20rpx 0;
  display: flex;
  flex-wrap: wrap;

  .lib {
    width: 150rpx;
    margin-bottom: 20rpx;
    margin-right: 40rpx;
    display: flex;
    flex-direction: column;
    position: relative;
    .close2_img {
      position: absolute;
      top: -15rpx;
      right: -15rpx;
      width: 30rpx;
      height: 30rpx;
    }
    image {
      border-radius: 20rpx;
      width: 150rpx;
      height: 150rpx;
    }
  }
}
</style>
